package com.xmy.dem01;
// 基本的卖票案例


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 真正的多线程开发，企业级开发中，线程就是一个单独的资源类，没有任何附属操作！
 * 资源类中包含属性和方法。
 */
public class SaleTicketDemo2 {
    public static void main(String[] args) {
        /*Ticket ticket = new Ticket();
        new Thread(ticket,"售票窗口A").start();
        new Thread(ticket,"售票窗口B").start();
        new Thread(ticket,"售票窗口C").start();
        new Thread(ticket,"售票窗口D").start();*/
        //并发：多个线程操作同一个资源
        Tickets2 tickets = new Tickets2();

        new Thread(()->{
            while (true){
//                try {
//                    Thread.sleep(50);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                tickets.sale();
            }
        },"售票窗口A").start();

        new Thread(()->{
            while (true){
//                try {
//                    Thread.sleep(50);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                tickets.sale();
            }
        },"售票窗口B").start();

        new Thread(()->{
            while (true){
//                try {
//                    Thread.sleep(50);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                tickets.sale();
            }
        },"售票窗口C").start();
    }
}

/**
 * 资源类 OOP
 */
class Tickets2 {
    //属性
    private int number = 50;

    //Lock锁
    Lock lock = new ReentrantLock();

    //卖票的方法
    public void sale(){
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.lock();//加锁
        try {
            if (number>0){
                System.out.println(Thread.currentThread().getName()+"出票成功，剩余"+--number+"张票");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //释放锁
        }

    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

//传统的实现多线程售票的方法
//class Ticket implements Runnable{
//
//    private int tickets=100;
//
//    @Override
//    public  void  run() {
//        while (tickets>0){
//            synchronized (this){
//                if (tickets>0) {
//                    System.out.println(Thread.currentThread().getName()
//                            + "出票成功，剩余" + --tickets + "张票");
//                    try {
//                        this.wait(50);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//    }
//}
